﻿@using AliasVault.WorkerStatus.Database
@inherits MainBase

@foreach (var service in Services)
{
    <button @onclick="() => ServiceClick(service.Name)"
            class="@GetServiceButtonClasses(service) mx-3 inline-flex items-center justify-center rounded-xl px-8 py-2 text-white"
            disabled="@(!service.IsHeartBeatValid)"
            title="@GetButtonTooltip(service)">
        <span>@service.DisplayName</span>
        @if (service.IsHeartBeatValid && service.CurrentStatus != service.DesiredStatus && !string.IsNullOrEmpty(service.DesiredStatus))
        {
            <svg class="animate-spin ml-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
        }
    </button>
}

@code {
    /// <summary>
    /// The names of the services to display.
    /// </summary>
    [Parameter]
    public List<string> ServiceNames { get; set; } = ["AliasVault.SmtpService", "AliasVault.TaskRunner"];

    /// <summary>
    /// The display names of the services to display.
    /// </summary>
    [Parameter]
    public Dictionary<string, string> ServiceDisplayNames { get; set; } = new();

    /// <summary>
    /// The statuses of the services.
    /// </summary>
    private List<WorkerServiceStatus> ServiceStatus = [];

    /// <summary>
    /// Whether the page is initializing.
    /// </summary>
    private bool InitInProgress;

    /// <summary>
    /// The interval to refresh the page.
    /// </summary>
    private readonly int AutoRefreshInterval = 5000;
    private CancellationTokenSource? _timerCancellationTokenSource;

    /// <summary>
    /// The state of a service.
    /// </summary>
    private sealed class ServiceState
    {
        public string Name { get; set; } = "";
        public string DisplayName { get; set; } = "";
        public string CurrentStatus { get; set; } = "";
        public string DesiredStatus { get; set; } = "";
        public bool IsHeartBeatValid { get; set; }
    }

    private List<ServiceState> Services { get; set; } = [];

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        Services = ServiceNames.Select(name => new ServiceState
        {
            Name = name,
            DisplayName = ServiceDisplayNames.GetValueOrDefault(name, name)
        }).ToList();

        await base.OnInitializedAsync();
    }

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            _timerCancellationTokenSource = new CancellationTokenSource();
            _ = RunPeriodicRefreshAsync(_timerCancellationTokenSource.Token);
        }
    }

    /// <inheritdoc />
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if (disposing)
        {
            _timerCancellationTokenSource?.Cancel();
            _timerCancellationTokenSource?.Dispose();
        }
    }

    /// <summary>
    /// Checks if the heartbeat is valid (within the last 5 minutes).
    /// </summary>
    private static bool IsHeartbeatValid(DateTime lastHeartbeat)
    {
        return DateTime.UtcNow <= lastHeartbeat.AddMinutes(5);
    }

    /// <summary>
    /// Gets the CSS classes for a service button based on its current state.
    /// </summary>
    private static string GetServiceButtonClasses(ServiceState service)
    {
        string buttonClass = "cursor-pointer ";

        if (!service.IsHeartBeatValid)
        {
            buttonClass += "bg-gray-600";
        }
        else if (service.CurrentStatus == "Started" && (service.DesiredStatus == string.Empty || service.DesiredStatus == "Started"))
        {
            buttonClass += "bg-green-600";
        }
        else if (service.CurrentStatus == "Stopping" || (service.DesiredStatus == "Stopped" && service.CurrentStatus != service.DesiredStatus))
        {
            buttonClass += "bg-red-500";
        }
        else if (service.CurrentStatus == "Starting" || (service.DesiredStatus == "Started" && service.CurrentStatus != service.DesiredStatus))
        {
            buttonClass += "bg-emerald-500";
        }
        else if (service.DesiredStatus == "Stopped" && (service.DesiredStatus == string.Empty || service.DesiredStatus == "Stopped"))
        {
            buttonClass += "bg-red-600";
        }

        return buttonClass;
    }

    /// <summary>
    /// Gets the tooltip text for a service button based on its last heartbeat.
    /// </summary>
    private static string GetButtonTooltip(ServiceState service)
    {
        if (!service.IsHeartBeatValid)
        {
            return "Heartbeat offline";
        }

        var statusMessages = new Dictionary<string, string>
        {
            { "Started", "Service is running" },
            { "Starting", "Service is starting..." },
            { "Stopped", "Service is stopped" },
            { "Stopping", "Service is stopping..." }
        };

        return statusMessages.GetValueOrDefault(service.CurrentStatus, string.Empty);
    }

    /// <summary>
    /// Handles a click on a service button.
    /// </summary>
    private async Task ServiceClick(string serviceName)
    {
        var service = Services.First(s => s.Name == serviceName);

        if (!service.IsHeartBeatValid)
        {
            return;
        }

        // If service not started and not starting, clicking should start it. Otherwise, stop it.
        if (service.CurrentStatus == "Started" || service.DesiredStatus == "Started")
        {
            service.DesiredStatus = "Stopped";
        }
        else
        {
            service.DesiredStatus = "Started";
        }
        StateHasChanged();

        await UpdateServiceStatus(serviceName, service.DesiredStatus);
        service.CurrentStatus = service.DesiredStatus;

        StateHasChanged();
    }

    /// <summary>
    /// Initializes the page.
    /// </summary>
    private async Task InitPage()
    {
        if (InitInProgress)
        {
            return;
        }

        try
        {
            InitInProgress = true;
            await using var dbContext = await DbContextFactory.CreateDbContextAsync();
            ServiceStatus = await dbContext.WorkerServiceStatuses.ToListAsync();

            foreach (var service in Services)
            {
                var entry = ServiceStatus.Find(x => x.ServiceName == service.Name);
                if (entry != null)
                {
                    service.IsHeartBeatValid = IsHeartbeatValid(entry.Heartbeat);
                    service.CurrentStatus = entry.CurrentStatus;
                    service.DesiredStatus = entry.DesiredStatus;
                }
            }

            await InvokeAsync(StateHasChanged);
        }
        finally
        {
            InitInProgress = false;
        }
    }

    /// <summary>
    /// Updates the status of a service.
    /// </summary>
    private async Task<bool> UpdateServiceStatus(string serviceName, string desiredStatus)
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        var entry = await dbContext.WorkerServiceStatuses.Where(x => x.ServiceName == serviceName).FirstOrDefaultAsync();
        if (entry != null)
        {
            entry.DesiredStatus = desiredStatus;
            await dbContext.SaveChangesAsync();

            var timeout = DateTime.UtcNow.AddSeconds(30);
            while (true)
            {
                if (DateTime.UtcNow > timeout)
                {
                    return false;
                }

                await using var dbContextInner = await DbContextFactory.CreateDbContextAsync();
                var check = await dbContextInner.WorkerServiceStatuses.Where(x => x.ServiceName == serviceName).FirstAsync();
                if (check.CurrentStatus == entry.DesiredStatus)
                {
                    return true;
                }
                await Task.Delay(1000);
            }
        }

        return false;
    }

    /// <summary>
    /// Refreshes the service status periodically.
    /// </summary>
    private async Task RunPeriodicRefreshAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            await InitPage();
            await Task.Delay(AutoRefreshInterval, cancellationToken);
        }
    }
}
